<template>
  <div
      class="task-card"
      :data-list-id="taskList.id"
      :class="{ active, 'empty-card': taskList.tasks.length === 0, 'hidden-card': !taskList.visible }"
      @click="$emit('click')"
  >
    <div class="card-header">
      <div class="header-first-row">
        <h3
            ref="titleRef"
            class="card-title"
            :contenteditable="taskList.editingName"
            @click.stop="$emit('start-editing-name')"
            @blur="handleSaveName"
            @keydown.enter.prevent="handleSaveName"
            spellcheck="false"
            v-if="taskList.isTitleVisible"
            :style="{ opacity: taskList.animationState === 'appearing' ? 0 : 1, transition: 'opacity 0.2s ease 0.1s' }"
        >{{ taskList.name }}</h3>

        <div class="menu-container">
          <el-button
              class="header-menu-btn"
              size="small"
              :icon="More"
              @click.stop="toggleMenu($event)"
          />

          <div
              class="card-options-menu"
              v-if="showMenu"
              :style="{ top: menuTop + 'px', right: menuRight + 'px' }"
              @click.stop
          >
            <div class="menu-item move-item" @click.stop="$emit('move-card')">
              移动任务项
            </div>
            <div class="menu-item delete-item" @click.stop="$emit('delete-card')">
              删除
            </div>
          </div>
        </div>
      </div>

      <div class="header-second-row" v-if="taskList.isTitleVisible">
        <a
            href="javascript:;"
            class="add-task-link"
            @click.stop="$emit('add-task')"
            :style="{ opacity: taskList.animationState === 'appearing' ? 0 : 1, transition: 'opacity 0.2s ease 0.15s' }"
        >
          <el-icon class="add-icon"><Plus /></el-icon>
          <span>添加任务</span>
        </a>
      </div>
    </div>

    <div class="card-body" :class="{ 'empty-body': taskList.tasks.length === 0 }" v-if="taskList.isTitleVisible" style="overflow-y: auto;">
      <div v-if="taskList.tasks.length === 0" class="empty-tasks">
        <img src="@/assets/empty-tasks.jpg" alt="暂无任务" class="empty-img" />
        <p class="empty-text">还没有任务呢</p>
        <p class="empty-subtext">添加待办事项，并追踪所有待办事项</p>
      </div>

      <div v-else class="tasks-list" ref="tasksListRef">
        <div class="incomplete-tasks">
          <TaskItem
              v-for="(task, taskIndex) in incompleteTasks"
              :key="task.id"
              :task="task"
              :task-index="getOriginalIndex(task.id)"
              :list-index="listIndex"
              @task-complete="(checked) => handleTaskComplete(listIndex, getOriginalIndex(task.id), checked)"
              @start-editing="$emit('start-editing', { taskIndex: getOriginalIndex(task.id), type: $event.type, event: $event.event })"
              @save-editing="$emit('save-editing', { taskIndex: getOriginalIndex(task.id), type: $event.type, event: $event.event })"
              @title-enter="$emit('title-enter', getOriginalIndex(task.id))"
              @navigate-to-desc="$emit('navigate-to-desc', getOriginalIndex(task.id))"
              @navigate-to-title="$emit('navigate-to-title', getOriginalIndex(task.id))"
              @set-date="$emit('set-date', { taskIndex: getOriginalIndex(task.id), date: $event })"
              @update-show-date-mode="(payload) => emit('update-show-date-mode', getOriginalIndex(task.id), payload.showAsText)"
              @toggle-options="$emit('toggle-options', { taskIndex: getOriginalIndex(task.id), event: $event })"
              @delete-task="$emit('delete-task', getOriginalIndex(task.id))"
              :active-calendar-task-id="activeCalendarTaskId"
              @set-active-calendar="$emit('set-active-calendar', $event)"
          />
        </div>

        <div v-if="completedTasks.length > 0" class="completed-separator">
          <span>已完成</span>
        </div>

        <div class="completed-tasks">
          <TaskItem
              v-for="(task, taskIndex) in completedTasks"
              :key="task.id"
              :task="task"
              :task-index="getOriginalIndex(task.id)"
              :list-index="listIndex"
              @task-complete="(checked) => handleTaskComplete(listIndex, getOriginalIndex(task.id), checked)"
              @start-editing="$emit('start-editing', { taskIndex: getOriginalIndex(task.id), type: $event.type, event: $event.event })"
              @save-editing="$emit('save-editing', { taskIndex: getOriginalIndex(task.id), type: $event.type, event: $event.event })"
              @title-enter="$emit('title-enter', getOriginalIndex(task.id))"
              @navigate-to-desc="$emit('navigate-to-desc', getOriginalIndex(task.id))"
              @navigate-to-title="$emit('navigate-to-title', getOriginalIndex(task.id))"
              @set-date="$emit('set-date', { taskIndex: getOriginalIndex(task.id), date: $event })"
              @update-show-date-mode="(payload) => emit('update-show-date-mode', getOriginalIndex(task.id), payload.showAsText)"
              @toggle-options="$emit('toggle-options', { taskIndex: getOriginalIndex(task.id), event: $event })"
              @delete-task="$emit('delete-task', getOriginalIndex(task.id))"
              :active-calendar-task-id="activeCalendarTaskId"
              @set-active-calendar="$emit('set-active-calendar', $event)"
          />
        </div>
      </div>
    </div>

    <div class="card-footer"></div>
  </div>
</template>

<script lang="ts" setup>
import { More, Plus } from '@element-plus/icons-vue'
import TaskItem from './TaskItem.vue'
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import type { Task, TaskList } from '@/types/taskList'

const titleRef = ref<HTMLElement | null>(null)
const showMenu = ref(false)
const menuTop = ref(0)
const menuRight = ref(0)
const tasksListRef = ref<HTMLDivElement | null>(null)

const props = defineProps<{
  activeCalendarTaskId: string | null
  taskList: TaskList
  listIndex: number
  active: boolean
  maxCardHeight: number
  cardFixedHeight: number
  tasksListPadding: number
  tasksListGap: number
}>()

const emit = defineEmits<{
  (e: 'click'): void
  (e: 'add-task'): void
  (e: 'start-editing-name'): void
  (e: 'save-name', newName: string): void
  (e: 'task-complete', listIndex: number, taskIndex: number, completed: boolean): void
  (e: 'start-editing', payload: { taskIndex: number; type: 'title' | 'desc'; event: Event }): void
  (e: 'save-editing', payload: { taskIndex: number; type: 'title' | 'desc'; event: Event }): void
  (e: 'title-enter', taskIndex: number): void
  (e: 'navigate-to-desc', taskIndex: number): void
  (e: 'navigate-to-title', taskIndex: number): void
  (e: 'set-date', payload: { taskIndex: number; date: 'today' | 'tomorrow' | string }): void
  (e: 'toggle-options', payload: { taskIndex: number; event: MouseEvent }): void
  (e: 'delete-task', taskIndex: number): void
  (e: 'set-active-calendar', taskId: string | null): void
  (e: 'update-show-date-mode', taskIndex: number, showAsText: boolean): void
  (e: 'delete-card'): void
  (e: 'move-card'): void
}>()

const incompleteTasks = computed(() => {
  return props.taskList.tasks.filter(task => !task.completed)
})

const completedTasks = computed(() => {
  return props.taskList.tasks.filter(task => task.completed)
})

const getOriginalIndex = (taskId: string) => {
  return props.taskList.tasks.findIndex(task => task.id === taskId)
}

const handleSaveName = () => {
  if (titleRef.value) {
    const newName = titleRef.value.innerText.trim()
    emit('save-name', newName)
  }
}

const toggleMenu = (event: MouseEvent) => {
  event.stopPropagation()
  if (showMenu.value) {
    showMenu.value = false
    return
  }

  const buttonRect = (event.target as HTMLElement).getBoundingClientRect()
  const cardRect = (event.currentTarget as HTMLElement).closest('.task-card')?.getBoundingClientRect()

  if (cardRect) {
    menuTop.value = buttonRect.bottom - cardRect.top + 5
    menuRight.value = cardRect.right - buttonRect.right + 5
    showMenu.value = true
  }
}

const handleTaskComplete = (listIndex: number, taskIndex: number, checked: boolean) => {
  // 直接触发事件，让父组件通过 store 更新状态（不要直接修改 props）
  emit('task-complete', listIndex, taskIndex, checked);
};

onMounted(() => {
  const handleClickOutside = (e: MouseEvent) => {
    const menuEl = document.querySelector('.card-options-menu')
    const btnEl = document.querySelector('.header-menu-btn')

    if (
        showMenu.value &&
        menuEl &&
        !menuEl.contains(e.target as Node) &&
        btnEl &&
        !btnEl.contains(e.target as Node)
    ) {
      showMenu.value = false
    }
  }

  document.addEventListener('click', handleClickOutside)

  return () => {
    document.removeEventListener('click', handleClickOutside)
  }
})

watch(
    () => props.taskList.tasks.length,
    (newLength, oldLength) => {
      if (newLength > oldLength && tasksListRef.value) {
        nextTick(() => {
          const lastTask = tasksListRef.value?.lastElementChild
          if (lastTask) {
            lastTask.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
            const editable = lastTask.querySelector('[contenteditable="true"]') as HTMLElement
            if (editable) {
              editable.focus()
            }
          }
        })
      }
    }
)
</script>

<style scoped>
.menu-container {
  position: relative;
}

.card-options-menu {
  position: absolute;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 160px;
  z-index: 100;
  padding: 4px 0;
  border: 1px solid #eee;
}

.menu-item {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

.delete-item {
  color: #ff4d4f;
  border-top: 1px solid #eee;
  margin-top: 4px;
  padding-top: 10px;
}

.move-item {
  padding-bottom: 10px;
}

.task-card {
  width: 450px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  display: flex;
  flex-direction: column;
  position: relative;
  height: calc(85% - 20px);
  overflow: auto;
  flex-shrink: 0;
  margin: 0 10px;
}

.task-card.active {
  outline: 2px solid #1976d2;
  outline-offset: -2px;
  box-shadow: 0 6px 24px rgba(25, 118, 210, 0.15);
  transform: translateY(-4px);
  z-index: 10;
}

.task-card.hidden-card {
  opacity: 0;
  width: 0 !important;
  margin: 0 !important;
  padding: 0;
  overflow: hidden;
  border: none;
  box-shadow: none;
  transition:
      opacity 0.4s ease,
      width 0.4s cubic-bezier(0.25, 0.8, 0.25, 1),
      margin 0.4s cubic-bezier(0.25, 0.8, 0.25, 1),
      padding 0.4s ease;
}

.card-header {
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12px;
  height: 100px;
  box-sizing: border-box;
  background-color: white;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.card-footer {
  height: 5px;
  padding: 0 20px;
  background-color: white;
  border-top: 0.5px solid #f0f0f0;
  border-bottom-left-radius: 12px;
  border-bottom-right-radius: 12px;
  box-sizing: border-box;
}

.header-first-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #333;
  display: block;
  min-width: 80px;
}

.card-title[contenteditable="true"] {
  border-bottom: 1px dashed #1976d2;
  padding-bottom: 2px;
  display: inline-block;
  spellcheck: false !important;
}

.card-title[contenteditable="true"]:focus {
  border-bottom: 1px solid #1976d2;
  background-color: rgba(227, 242, 253, 0.3);
  outline: none;
}

.header-menu-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  border-radius: 6px;
  background-color: transparent;
  color: #666;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none !important;
}

.header-menu-btn:hover {
  background-color: #f0f0f0;
  color: #333;
}

.header-second-row {
  width: 100%;
}

.add-task-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: #1976d2;
  font-size: 15px;
  font-weight: 500;
  text-decoration: none;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.add-task-link:hover {
  background-color: #ffffff;
}

.add-icon {
  font-size: 16px;
}

.card-body {
  padding: 20px;
  box-sizing: border-box;
  overflow-x: hidden;
  flex: 1;
  background-color: white;
}

.card-body::-webkit-scrollbar {
  width: 6px;
}

.card-body::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 3px;
}

.card-body::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}

.card-body::-webkit-scrollbar-thumb:hover {
  background-color: #aaa;
}

.card-body:not(:hover)::-webkit-scrollbar-thumb {
  background-color: transparent;
}

.card-body:hover::-webkit-scrollbar-thumb {
  background-color: #ccc;
}

.card-body.empty-body {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.empty-tasks {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px 24px;
  text-align: center;
  width: 100%;
  height: 100%;
  color: #666;
}

.empty-img {
  width: 120px;
  height: 120px;
  margin-bottom: 16px;
  opacity: 0.7;
  object-fit: contain;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #333;
}

.empty-subtext {
  font-size: 13px;
  color: #666;
  margin: 0;
  max-width: 240px;
}

.tasks-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.completed-separator {
  margin: 16px 0 8px;
  padding: 4px 0;
  position: relative;
}

.completed-separator::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background-color: #1976d2; /* 加深分隔线颜色 */
  z-index: 1;
}

.completed-separator span {
  position: relative;
  z-index: 2;
  font-size: 14px;
  font-weight: 600;
  color: #1976d2;
  background-color: white;
  padding: 0 12px;
  letter-spacing: 0.5px;
}

.completed-tasks {
  margin-top: 8px;
}
</style>